image-20190810194819062

image-20190810194831797


1、新建RabbitMqTopicConfig配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Configuration
public class {
//只接一个topic
final static String message = "topic.message";
//接收多个topic
final static String messages = "topic.messages";

//队列
@Bean
public Queue queueMessage() {
return new Queue(RabbitMqTopicConfig.message);
}

@Bean
public Queue queueMessages() {
return new Queue(RabbitMqTopicConfig.messages);
}

// 新建 TopicExchange
@Bean
TopicExchange exchange() {
return new TopicExchange("exchange");
}

//绑定交换机
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
}


//绑定交换机 以topic.#为路由 queueMessages就是方法名
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
//这里的#表示零个或多个词。
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}

在SendController添加发送消息方法:

1
2
3
4
5
6
7

// 交换机
//路由key

this.amqpTemplate.convertAndSend("exchange", "topic.messages", context);

this.amqpTemplate.convertAndSend("exchange", "topic.message", context);

接受放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

@Component
@RabbitListener(queues = "topic.message")
public class TopicReceiver1 {
@RabbitHandler
public void process(String msg) {
}






@Component
@RabbitListener(queues = "topic.messages")
public class TopicReceiver2 {
@RabbitHandler
public void process(String msg) {

}
1
,队列topic.message只能匹配topic.message的路由。而topic.messages匹配路由规则是topic.#,所以它可以匹配topic.开头的全部路由。而topic.#发送的消息也只能是topic.#的接受者才能接收

image-20190810201547354